<template>
    <view class="head-container">
        <view class="title">{{ timeName }}</view>
        <view class="description">{{ description }}</view>
        
        <view class="search-bar-box">
            <!-- TODO 加弹窗 光标进入的时候显示内容-->
            <eui-search-bar
                radius="20" 
                placeholder="搜一搜商品/功能/审批/邮件…" 
                @confirm="handleConfirm" 
                bgColor="#ffffff"
                v-model="c_search"
                @clear="clearSearch"
                @focus="isPopupVisible = true"
                class="search-input"
                searchHeight="72"
                placeholderStyle="color:#CCCCCC;font-size: 26rpx;"
            >
                <template #searchFields>
                <eui-button title="dsafsadf"></eui-button>
                </template>
            </eui-search-bar>
        </view>
        <!-- 蒙层 -->
        <view class="mask-box" :class="[props.theme]">
            <transition name="fade">
                <view v-show="isPopupVisible" class="fade-popup" :style="{ height: fadeHeight + 'px'}" @click="closePopup">
                    <eui-card topMargin="10" vPadding="28" @click.stop="handleClick">
                        <scroll-view scroll-y :style="{height: scrollHeight + 'px'}">
                            <view class="mask-title flex-row-between">
                                <view class="fade-title">历史搜索</view>
                                <view class="iconfont icon-shanchu" @click="removeHistory" style="font-size: 30rpx;"></view>
                            </view>
                            <!-- 历史列表 -->
                            <view  class="tag-box flex-row">
                                <eui-tag 
                                    :text="item" 
                                    plain
                                    plainFill
                                    type="info"
                                    v-for="(item, index) in historyList" 
                                    :key="index"
                                    @click="handleHistory(item)"
                                    bgColor="rgb(249, 249, 248)" 
                                    color="#000000"
                                    borderColor="#ffffff"
                                    shape="circle"
                                ></eui-tag>

                            </view>
                            <!-- 查询内容 -->
                            <template v-for="(item, index) in searchList" :key="index">
                                <view v-if="item.data.length > 0">
                                    <view class="fade-title">{{ item.title }}</view>
                                    <view class="tag-box">
                                        <eui-tag 
                                            plain
                                            plainFill
                                            type="info"
                                            :text="k.title" 
                                            v-for="(k, kIndex) in item.data" 
                                            :key="kIndex"
                                            @click="handleTag(item.title, k)"
                                            bgColor="rgb(249, 249, 248)" 
                                            color="#000000"
                                            borderColor="#ffffff"
                                            shape="circle"
                                        ></eui-tag>
                    
                                    </view>
                                </view>
                            </template>
                            <!-- <view class="tips note-data-tips" >未找到...相关的信息！</view> -->
                        </scroll-view>
                    </eui-card>
                </view>
            </transition>
        </view>
    </view>
    
</template>
  
<script setup lang="ts">
import service from '../common/service';
import { useMainStore } from '../store/modules/store';
import {  ref, onMounted, computed, getCurrentInstance } from 'vue';
import { onLoad, onShow } from "@dcloudio/uni-app";
import { useLoginStore } from '../store/modules/useLoginStore';
// import Items from '@/pages/RdsViews/patrolWorkbench/items.vue';
import { useSystemInfoStore } from '../store/useSystemInfo';
const LoginStore = useLoginStore();
const mainStore = useMainStore();
const systemInfoStore = useSystemInfoStore(); // 系统参数
/**
 *  HomeHead 头部显示区域
 *  @property {string} user = 登录人
 */

interface Props {
  user: string,
  theme: string
}
const props = defineProps<Props>();

const timeName = ref('');
const description = ref('欢迎使用管易通，移动办公更轻松~');
const updateTimeName = ():string => {
    const currentHour = new Date().getHours(); // 获取当前小时
    let timeName = '';
    if (currentHour >= 6 && currentHour < 12) {
        timeName = '上午好'
    } else if (currentHour >= 12 && currentHour < 18) {
        timeName = '下午好';
    } else if (currentHour >= 18 && currentHour < 24) {
        timeName = '晚上好';
    } else {
        timeName = '你好';
    }
    return timeName + '，'+ props.user;
};
const scrollHeight = ref(0);
// 搜索
const searchPopup = ref<any>(null);
const c_search = ref('');
// 蒙层
const fadeHeight = ref(500);
const isPopupVisible = ref(false)
// computed(()=> {
//     return c_search.value.length > 0;
// })


// 搜索信息
const historyList = ref([]);
const searchList = ref([
    {
        title: '人员信息',
        data: []
    },
    {
        title: '功能',
        data: []
    },
    {
        title: '我的审批',
        data: []
    },
    {
        title: '我的邮件',
        data: []
    },
]);

// 删除历史
const removeHistory = () => {
    uni.removeStorageSync('searchlist');
    historyList.value = [];
}


/**
 * 蒙层初始化高度
 */
const popupHeight = ref('');
const initScrollView =() => {
	const instance = getCurrentInstance();
    popupHeight.value = 470 + 'px';
    const query = uni.createSelectorQuery().in(instance);
    setTimeout(()=> {
        query.select('.search-bar-box').boundingClientRect(data => {
            var _heigth = systemInfoStore?.systemInfo?.windowHeight || 600;
            fadeHeight.value = _heigth - (data?.top + data?.height);
            scrollHeight.value = _heigth - (data?.top + data?.height) - 100;
        }).exec();
    }, 1000)
}

const handleClick = () => {
    // console.log('按钮被点击，事件冒泡被阻止');
}

// 查询人员信息
const QueryPerson = () => {
    service.enjoyShowLoading('正在查询...');
    let request = {
        url: LoginStore.EnjoyMain,
        data: {
            UniqueKey: "管易通40通讯录",
            MethodName: "GetUserInfoList",
            ObjectData: {
                whereList: [{
                    c_type_name: '',
					c_col: 'p.c_name',
					c_oper: '相似',
					c_value: '%' + c_search.value.trim() + '%',
					c_col_dtype: "System.String",
					c_logic: "或者",
					c_left: "",
                }]
            },
        },
    }
    service.request(request, (res) => {
        service.enjoyHideLoading();
        if (res && res.data) {
            if (!res.data.HasException) {
                let ObjectData = res.data.ObjectData.ReturnObject;
                ObjectData = Array.isArray(ObjectData) ? ObjectData.map(obj => ({
                    ...obj,
                    title: obj.c_name,
                })) : [];
                const index = searchList.value.findIndex(item => item.title === '人员信息');
                searchList.value[index].data = ObjectData;
            } else {
                service.enjoyShowToast(res.data.Exception.Message)
            }
        }
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}

// 查询功能
const QueryFunction = () => {
    service.enjoyShowLoading('正在查询...');
    let request = {
        url: LoginStore.EnjoyMain,
        data: {
            UniqueKey: "管易通40公共",
            MethodName: "QueryFunction",
            ObjectData: {
                // 用于苹果审核特殊处理获取不到用户时默认按0006账号获取this.loginInfo.sUser,
                sMkUser: mainStore.loginInfo.sUser ? mainStore.loginInfo.sUser : '0006',
                sExtend: c_search.value,
            },
        },
    }
    service.request(request, (res) => {
        service.enjoyHideLoading();
        if (res && res.data) {
            if (!res.data.HasException) {
                let ObjectData = res.data.ObjectData;
                const index = searchList.value.findIndex(item => item.title === '功能');

                ObjectData = Array.isArray(ObjectData) ? ObjectData.map(obj => ({
                    ...obj,
                    title: obj.c_title,
                })) : [];

                searchList.value[index].data = ObjectData;
            } else {
                service.enjoyShowToast(res.data.Exception.Message)
            }
            
        }
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}
// 查询我的审批
const QueryApprove = () => {
    service.enjoyShowLoading('正在查询...');
    let request = {
        url: LoginStore.EnjoyMain,
        data: {
            UniqueKey: "管易通40公共",
            MethodName: "QueryApprove",
            ObjectData: {
                // 用于苹果审核特殊处理获取不到用户时默认按0006账号获取this.loginInfo.sUser,
                sMkUser: mainStore.loginInfo.sUser ? mainStore.loginInfo.sUser : '0006',
                sExtend: c_search.value,
            },
        },
    }
    service.request(request, (res) => {
        service.enjoyHideLoading();

        if (res && res.data) {
            if (!res.data.HasException) {
                let ObjectData = res.data.ObjectData;
                const index = searchList.value.findIndex(item => item.title === '我的审批');
                ObjectData = Array.isArray(ObjectData) ? ObjectData.map(obj => ({
                    ...obj,
                    title: obj.c_title,
                })) : [];

                searchList.value[index].data = ObjectData || [];
            } else {
                service.enjoyShowToast(res.data.Exception.Message)
            }
        }
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}

// 查询我的邮件
const QueryEMails = () => {
    service.enjoyShowLoading('正在查询...');
    let request = {
        url: LoginStore.EnjoyMain,
        data: {
            UniqueKey: "管易通40内部邮件",
            MethodName: "QueryEMails",
            ObjectData: {
                IsNotPage: false,
                Sql: null,
                PageSize: 10,
                CurrentPage: 1,
                c_read_status: null,
                c_type: "收件箱",
                c_title: c_search.value,
                c_sender: mainStore.loginInfo.sUser ? mainStore.loginInfo.sUser : '0006',
                c_send_start_dt: '',
                c_send_end_dt: ''
            },
        },
    }
    service.request(request, (res) => {
        service.enjoyHideLoading();
        if (res && res.data) {
            if (!res.data.HasException) {
                let ObjectData = res.data.ObjectData.ReturnObject;
                const index = searchList.value.findIndex(item => item.title === '我的邮件');
                ObjectData = Array.isArray(ObjectData) ? ObjectData.map(obj => ({
                    ...obj,
                    title: obj.c_title,
                })) : [];
                searchList.value[index].data = ObjectData || [];
            } else {
                service.enjoyShowToast(res.data.Exception.Message)
            }
        }
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}


// 系统参数
const c_showValue = ref<string>(''); // 系统参数 管易通首页搜索框可搜索内容
const GetSyscfg = () => {
    service.enjoyShowLoading('正在查询...');
    let request = {
        url: LoginStore.EnjoyMain,
        data: {
            UniqueKey: "管易通40公共",
            ObjectData: {
                whereList: [{
                    c_type_name: '',
                    c_col: 'c_name',
                    c_oper: '=',
                    c_value: "管易通界面展示水印内容",
                    c_col_dtype: "System.String",
                    c_logic: "或者",
                }, {
                    c_type_name: '',
                    c_col: 'c_name',
                    c_oper: '=',
                    c_value: "管易通首页搜索框可搜索内容",
                    c_col_dtype: "System.String",
                    c_logic: "或者",
                }, {
                    c_type_name: '',
                    c_col: 'c_name',
                    c_oper: '=',
                    c_value: "管e通用户遵守企业数据保密协议提醒内容",
                    c_col_dtype: "System.String",
                    c_logic: "或者",
                }, {
                    c_type_name: '',
                    c_col: 'c_name',
                    c_oper: '=',
                    c_value: "管e通需要弹出用户遵守企业数据保密协议提醒的模块",
                    c_col_dtype: "System.String",
                    c_logic: "或者",
                }]
            },
            MethodName: "GetSyscfg",
        },
    }
    service.request(request, (res) => {
        service.enjoyHideLoading();
        if (res && res.data) {
            if (!res.data.HasException) {
                const ObjectData = res.data.ObjectData;
                if (ObjectData.ReturnObject && ObjectData.ReturnObject.length > 0) {
                    ObjectData.ReturnObject.forEach(item => {
                        if (item.c_name == '管易通首页搜索框可搜索内容') {
                            c_showValue.value = item.c_value;
                        }
                    })
                }
            } else {
                service.enjoyShowToast(res.data.Exception.Message)
            }
        }
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}

// 数据查询
type QueryFunctionType = () => void;
const queryFunctions: Record<string, QueryFunctionType> = {
    '人员': QueryPerson,
    '功能': QueryFunction,
    '审批': QueryApprove,
    '邮件': QueryEMails,
}
const queryList = () => {
    if (c_showValue.value) {
        // 分割字符串并去除空字符串和前后空格和过滤掉空字符串
        const keywords = c_showValue.value.split(',').map((keyword) => keyword.trim()).filter((keyword) => keyword);

        keywords.forEach((keyword) => {
            if (queryFunctions[keyword]) {
                queryFunctions[keyword](); // 直接调用查询函数
            }
        });
    } else {
        if (historyList.value.length > 0) {
            if (!historyList.value.some(item => item === c_search.value)) {
                historyList.value.push(c_search.value);
                uni.setStorageSync('searchlist', JSON.stringify(historyList.value));
            }
        } else {
            historyList.value.push(c_search.value);
        }

        QueryPerson();
        QueryFunction();
        QueryApprove();
        QueryEMails();
    }
}

// 回车
const handleConfirm = () => {
  console.log('回车了');
  
  if (c_search.value.length > 0) {
    queryList();
  }
}

const clearSearch = () => {
    c_search.value = '';
}
const handleHistory = (item) => {
    c_search.value = item;
    queryList();
}
const handleTag = (title: string, value:any) => {
    console.log(title, value);
    let url = "";
    switch(title) {
        case '人员信息': 
            url = `/pages/MainViews/user/contactDetail?userno=${value.c_userno}`;
            break;
        case '功能': 
            if (value.c_origin_type == '用户定义报表') {
                console.log('自定义报表暂无处理');
            } else if (value.c_origin_type == "系统固有" && value.c_ini_param == "integration") {
                console.log('帆软报表处理');
            } else if(value.c_origin_type == "系统固有" && value.c_ini_param == "MBMStorePC") {
                console.log('当前用户所属机构不是分店时，需要先选择一个登录的机构');
            } else if (value.c_title == '考勤管理'){
                console.log('考勤管理 待处理 请开启定位并重启管易通,才可进入该模块!');
            } else {
                mainStore.limitCodeIn(value.c_limitcode);
                let moduleInfo = encodeURIComponent(JSON.stringify(value));
                url =`${value.c_md_name}?moduleInfo=${moduleInfo}`;
            }
            break;
        case '我的审批': 
            GetApprovingInfoById(value) 
        // url = "/pages/OaViews/Approve/ApproveList?item=" + JSON.stringify(value) + "&current=0";
            break;
        case '我的邮件': 
            url = '/pages/OaViews/Email/EmailDetail?id=' + value.c_id + '&selType=收件箱&industryTabIndex=2&c_read_status=' + value.c_read_status
            break;
    }
    c_search.value = "";
    closePopup()
    if (url) {
        uni.navigateTo({
            url: url
        });
    }
}
// 获取审批
const GetApprovingInfoById = (item) => {
    service.enjoyShowLoading('正在查询...');
    console.log('点击了', item);
	let request = {
		url: LoginStore.EnjoyMain,
		data: {
			UniqueKey: "管易通40审批",
			ObjectData: {
				MsgRecvId: item.c_id,
				AppUserNo:  mainStore.loginInfo.sUser ? mainStore.loginInfo.sUser : '0006',
			},
			MethodName: "GetApprovingInfoById",
		},
	}
	service.request(request, (res) => {
        service.enjoyHideLoading();
		if (res && res.data) {
			if (!res.data.HasException) {
                const objectData =  res.data.ObjectData || [];
                let lstApproveBill = {};
                if (objectData.length > 0) {
                    const _arr = objectData.map(item => ({
                        ...item,
                        c_checked: false,
                        AppParamType: 3
                    }));

                    lstApproveBill = _arr[0];
                    if (_arr[0].ReadStatus == '未阅') {
                        UpdateApproveReadStatus(_arr[0]);
                    } else {
                        uni.navigateTo({
                            url: '/pages/OaViews/Approve/ApproveDetail?item=' + JSON.stringify(lstApproveBill) + '&tabIndex=0'
                        });
                    }
                }
			} else {
				service.enjoyShowToast(res.data.Exception.Message)
			}
		}
	}, () => {
        service.enjoyHideLoading();
		console.log('失败')
	});
}

// 更新审批阅读状态
const UpdateApproveReadStatus = (e) => {
    service.enjoyShowLoading('正在处理...');
    let request = {
        url: LoginStore.EnjoyMain,
        data: {
            UniqueKey: "管易通40审批",
            ObjectData: {
                AppRecvId: e.AppRecvId,
                MsgRecvId: e.MsgRecvId,
                MsgId: e.MsgId,
                AppUserNo: mainStore.loginInfo.sUser
            },
            MethodName: "UpdateApproveReadStatus",
        },
    }
    service.request(request, (res) => {
        service.enjoyHideLoading();
        if (res && res.data) {
            if (!res.data.HasException) {
                const ObjectData = res.data.ObjectData;
                e.ReadStatus = '已阅';
                uni.navigateTo({
                    url: '/pages/OaViews/Approve/ApproveDetail?item='+JSON.stringify(e)+ '&tabIndex=0'
                });
            } else {
                service.enjoyShowToast(res.data.Exception.Message)
            }
        }
    }, () => {
        service.enjoyHideLoading();
        console.log('失败')
    });
}
// 关闭蒙版
const closePopup = () => {
    console.log('点击关闭蒙版');
    isPopupVisible.value = false;
    searchList.value = ([{
        title: '人员信息',
        data: []
    }, {
        title: '功能',
        data: []
    }, {
        title: '我的审批',
        data: []
    }, {
        title: '我的邮件',
        data: []
    }]);
}

onMounted(() => {
  timeName.value = updateTimeName();
});

onLoad(() => {
    GetSyscfg()
})

onShow(() => {
    initScrollView();
    var list = uni.getStorageSync('searchlist') ? JSON.parse(uni.getStorageSync('searchlist')) :[];
    // console.log(642,'初始化啊',  list);
    historyList.value = list;
})

</script>
  

<style lang="scss" scoped>
.head-container {
  position: absolute;
  left: 48rpx;
  bottom: 32rpx;
  z-index: 99;
  width: calc(100% - 96rpx);
  .title {
      color: #fff;
      margin-bottom: 15rpx;
      font-weight: bold;
      font-size: 48rpx;
      box-sizing: border-box;
      width: calc(100% - 96rpx);
  }
  .description {
      margin-bottom: 51rpx;
      color: #fff;
      font-size: 30rpx;
      box-sizing: border-box;
  }
  ::v-deep .uni-searchbar-content {
    padding-top: 0 !important;
    padding-bottom: 0 !important;
  }
}
.search-input {
  ::v-deep .uni-searchbar__box-icon-search {
    padding-left: 40rpx;
  }
  ::v-deep .uni-searchbar__box-search-input {
    padding-left: 12rpx;
    font-family: PingFangSC, PingFang SC;
    font-weight: 400;
    font-size: 26rpx;
    color: #CCCCCC;
  }
}
.search-bar-box {
    ::v-deep .uni-input-input {
        color: #000000;
    }
}
// 蒙层
/* 淡入淡出动画 */
.fade-enter-active, .fade-leave-active {
  transition: opacity 0.5s ease;
}
.fade-enter-from, .fade-leave-to {
  opacity: 0;
}
.mask-box {
    position: relative;
    .iconfont {
        color: #000000;
    }
    .fade-popup {
        position: absolute;
        background: rgba(0, 0, 0, 0.5);
        padding-top: 24rpx;
        width: 100vw;
        height: 400rpx;
        z-index: 990;
        left: -48rpx;
        box-sizing: border-box;
        .mask-title {
            margin-bottom: 28rpx;
            height: 40rpx;
            line-height: 40rpx;
            color: #000000;
            font-size: 28rpx;
            .fade-title {
                margin-bottom: 0;
            }
        }
    }
    .search-popup-main {
        padding-top: 10rpx;
        box-sizing: border-box;
    }

    ::v-deep .list_cell {
        min-height: 100rpx;
    }
    .fade-title {
        margin-bottom: 28rpx;
        font-size: 28rpx;
        color: #000000;
        font-weight: 500;
        font-family: PingFangSC, PingFang SC;
    }
    .tips {
        margin-left: 40rpx;
        color: var(--theme-color);
        font-family: SourceHanSansCN, SourceHanSansCN;
        font-weight: 400;
        font-size: 24rpx;
    }
    .note-data-tips {
        height: 100rpx;
        line-height: 100rpx;
    }
    .tag-box {
        display: flex;
        flex-wrap: wrap;
        margin-bottom: 30rpx;
        ::v-deep .u-tag-wrapper {
            margin-bottom: 20rpx;
        }
        ::v-deep .u-tag--medium {
            padding: 0 20rpx;
            height: 52rpx;
            line-height: 52rpx;
            font-family: PingFangSC, PingFang SC;
            font-weight: 400;
            font-size: 24rpx;
        }
        ::v-deep .u-tag__text--medium {
            line-height: 30rpx;
            word-break: break-all;
        }
    }
}
</style>